package com.hongyi.app.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hongyi.app.entity.Permission;
import com.hongyi.app.entity.RolePermission;
import com.hongyi.app.entity.User;
import com.hongyi.app.entity.UserNo;
import com.hongyi.app.mapper.RolePermissionMapper;
import com.hongyi.app.mapper.UserMapper;
import com.hongyi.app.mapper.UserNoMapper;
import com.hongyi.app.service.UserService;
import com.sun.javafx.UnmodifiableArrayList;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.omg.PortableServer.ID_ASSIGNMENT_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.text.StyledEditorKit;
import java.util.ArrayList;
import java.util.List;

/**
 * @author HongYi
 */
@Slf4j
@Data
public class UserServiceImpl implements UserService {


    private UserMapper userMapper;
    private RolePermissionMapper rolePermissionMapper;
    private UserNoMapper userNoMapper;


    @Override
    public boolean checkUsername(String username) {

        return userMapper.selectByUsername(username) != null;
    }

    @Override
    public User login(String username, String password) {

        //根据账号查询用户记录是否存在
        User user = userMapper.selectByUsernameAndPassword(username, password);
        if (user == null) {
            return new User(-1, "账号或密码错误");
            //括号作用直接调用构造器进行设置参数
        }
        return user;
    }

    @Override
    public List<Permission> selectPermissionById(Integer id) {

        //根据用户id查询用户记录
        User user = userMapper.selectById(id);
        if (user == null) {
            log.info("该用户不存在，返回空List实例···");
            return new ArrayList<>();
        }

        //获取该用户的roleId
        Integer roleId = user.getRoleId();
        if (roleId == null) {
            log.info("该用户未赋于角色，返回空list实例");
            return new ArrayList<>();
        }

        //全查角色权限
        List<RolePermission> rolePermissions = rolePermissionMapper.selectByRoleId(roleId);
        if (rolePermissions == null) {
            log.info("该角色未被赋予任何权限，返回空List实例···");
            return new ArrayList<>();
        }

        //将 List<RolePermission>转换为 List<Permission>
        List<Permission> result = new ArrayList<>();
        rolePermissions.forEach(rp -> result.add(rp.getPermission()));

        return result;
    }

    @Override
    public User selectById(Integer id) {

        User user = userMapper.selectById(id);
        return user != null ? user : new User(-1, "用户不存在");
    }

    @Override
    public List<User> list() {
        List<User> result = userMapper.list();

        return result != null ? result : new ArrayList<>();
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int insert(User user) {
        //业务为添加一条User记录
        //按id排序，从UserNo表中查询一条可用编号
        UserNo userNo = userNoMapper.selectByStatus(1, "id");
        if (userNo == null) {
            log.info("当前无可用编号，返回0···");
            return 0;
        }

        //检查账号是否已被注册
        String username = user.getUsername();
        if (userMapper.selectByUsername(username) != null) {
            log.info("当前账号已被使用，返回0···");
            return 0;
        }

        //插入User,并判断是否成功
        if (userMapper.insert(user) <= 0) {
            log.info("用户信息添加失败，返回0···");
            return 0;
        }

        //将新增的用户的编号状态改为0，（表示该编号已被使用）
        userNo.setStatus(0);
        if (userNoMapper.updateById(userNo) <= 0) {
            throw new RuntimeException("编号修改异常，事务回滚···");
        }

        return 1;
    }

    @Override
    public int updateById(User user) {

        if (user.getId() == null) {
            log.warn("用户不存在,返回0···");
            return 0;
        }
        //账号和标号不能修改
        user.setUsername(null);
        user.setUserNoId(null);

        //修改用户基本信息
        if (userMapper.updateById(user) <= 0) {
            log.warn("用户信息修改失败，返回0···");
            return 0;
        }
        return 1;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int deleteById(Integer id) {

        User user = userMapper.selectById(id);
        //根据id查询用户是否存在
        if (user == null) {
            log.warn("用户不存在，返回0···");
            return 0;
        }
        // 将编号设置为零
        UserNo userNo = user.getUserNo();
        if (userNo != null) {
            userNo.setStatus(1);
            if (userNoMapper.updateById(userNo) <= 0) {
                throw new RuntimeException("用户编号修改失败，事务回滚···");
            }
        }

        //删除用户基本信息
        if (userMapper.deleteById(id) <= 0) {
            throw new RuntimeException("用户删除失败，事务回滚···");
        }
        return 1;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int deleteByIds(Integer[] ids) {

        Integer idsLength = ids.length;
        //判断ids是否为空，瑕疵：当id中有为零的值
        if (idsLength <= 0) {
            log.warn("删除操作失败，至少删除一个用户，返回-1");
            return -1;
        }

        //通过用户表主键批量查询用户编号表，
        List<User> users = userMapper.selectByIds(ids);
        if (users == null || users.size() != idsLength) {
            log.warn("用户记录查询失败,至少有一条user记录为空");
            return 0;
        }
        //批量查询用户编号主键
        List<Integer> userNos = new ArrayList<>();
        for (User user : users) {
            Integer userNo = user.getUserNoId();
            if (userNo != null) {
                userNos.add(userNo);
            }

        }
        //批量设置用户编号
        if (userNoMapper.setStatusById(userNos, 1) <= 0) {
            log.warn("至少有一条编号记录修改失败，返回0");
            return 0;
        }

        //批量删除user记录
        if (userMapper.delectByIds(ids) < idsLength) {
            log.warn("至少有一条user记录删除失败···，返回0");
            return 0;
        }

        return 1;
    }

    @Override
    public PageInfo<User> paging(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<User> list = userMapper.list();
        if (list != null) {
            return new PageInfo<>(list);
        }

        return new PageInfo<>();
    }


}
